// Package utils
// @Author: zhangdi
// @File: screen_size
// @Version: 1.0.0
// @Date: 2023/5/22 11:10
package utils

import (
	"errors"
	"fmt"
	"os/exec"
	"regexp"
	"runtime"
	"strconv"
	"strings"
)

// 加载user32.dll库
var (
	//user32                   = syscall.MustLoadDLL("user32.dll")
	//getSystemMetrics         = user32.MustFindProc("GetSystemMetrics")
	smCxScreen uintptr = 0
	smCyScreen uintptr = 1
)

// GetScreenSizeWin 获取屏幕尺寸的函数,已验证
func GetScreenSizeWin() (x int, y int, err error) {
	//width, _, err := getSystemMetrics.Call(smCxScreen)
	//height, _, err := getSystemMetrics.Call(smCyScreen)
	return 1280, 1024, err
}

// GetScreenSizeMacos 获取Linux的分辨率，未测试
func GetScreenSizeMacos() (width int, height int, err error) {
	width = 0
	height = 0
	out, err := exec.Command("system_profiler", "SPDisplaysDataType").Output()
	if err != nil {
		return width, height, fmt.Errorf("获取屏幕分辨率出错：", err)
	}

	// 使用正则表达式找到第一个 "Resolution" 行
	re := regexp.MustCompile(`Resolution:\s+(\d+)\s+x\s+(\d+)`)
	match := re.FindAllStringSubmatch(string(out), -1)

	if len(match) == 0 {
		return width, height, errors.New("错误：找不到匹配的分辨率信息")
	}

	widthStr := strings.TrimSpace(match[0][1])
	heightStr := strings.TrimSpace(match[0][2])

	_, err = fmt.Sscanf(widthStr+" "+heightStr, "%d %d", &width, &height)
	if err != nil {
		return width, height, fmt.Errorf("分辨率解析失败：", err)
	}

	return width, height, nil
}

// GetScreenSizeLinux 获取Linux的分辨率，未测试
func GetScreenSizeLinux() (int, int, error) {
	// 执行 xrandr 命令并捕获标准输出结果
	output, err := exec.Command("xrandr").Output()
	if err != nil {
		return 0, 0, err
	}

	// 查找带星号的输出行（代表当前屏幕）
	for _, line := range strings.Split(strings.TrimSpace(string(output)), "\n") {
		if strings.Contains(line, "*") {
			fields := strings.Fields(line)
			resolution := strings.Split(fields[0], "x")
			width := toInt(resolution[0])
			height := toInt(resolution[1])
			return width, height, nil
		}
	}

	return 0, 0, fmt.Errorf("screen size not found")
}

// 辅助函数将字符串转换为整数，忽略错误
func toInt(s string) int {
	i, _ := strconv.Atoi(s)
	return i
}
func GetScreenSize() (int, int, error) {
	switch runtime.GOOS {
	case "windows":
		return GetScreenSizeWin()
	case "darwin":
		return GetScreenSizeMacos()
	case "linux":
		return GetScreenSizeLinux()
	default:
		return 0, 0, fmt.Errorf("unsupported platform")
	}
}
